import React, { useState, useEffect } from 'react';
import { Table, Badge, SearchIcon, type TableColumn } from "@repo/ui";
import { DeviceInstanceStatus } from "@repo/api";
import type { DeviceInstance } from "@repo/api";
import styles from './DevicePage.module.css';

const DevicePage: React.FC = () => {
  const [devices, setDevices] = useState<DeviceInstance[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  const [statusFilter, setStatusFilter] = useState<string>('all');

  // 加载设备数据
  useEffect(() => {
    const loadDevices = async () => {
      try {
        setLoading(true);
        // TODO: 调用 API 获取设备实例数据
        // const response = await deviceService.getDeviceInstances();
        // setDevices(response.data);
        setDevices([]); // 暂时设为空数组
      } catch (error) {
        console.error('加载设备数据失败:', error);
      } finally {
        setLoading(false);
      }
    };

    loadDevices();
  }, []);

  const filteredDevices = devices.filter(device => {
    const matchesSearch = (device.device_name?.toLowerCase().includes(searchTerm.toLowerCase()) || false) ||
                         (device.device_type?.toLowerCase().includes(searchTerm.toLowerCase()) || false) ||
                         (device.location?.toLowerCase().includes(searchTerm.toLowerCase()) || false);
    const matchesStatus = statusFilter === 'all' || device.status === statusFilter;
    return matchesSearch && matchesStatus;
  });

  const getStatusBadge = (status: DeviceInstanceStatus) => {
    const statusConfig: Record<DeviceInstanceStatus, { text: string; variant: 'success' | 'default' | 'error' }> = {
      [DeviceInstanceStatus.ONLINE]: { text: '在线', variant: 'success' },
      [DeviceInstanceStatus.OFFLINE]: { text: '离线', variant: 'default' },
      [DeviceInstanceStatus.MAINTENANCE]: { text: '维护中', variant: 'error' },
      [DeviceInstanceStatus.DELETED]: { text: '已删除', variant: 'error' }
    };
    
    const config = statusConfig[status] || { text: '未知', variant: 'default' as const };
    return <Badge variant={config.variant} size="sm">{config.text}</Badge>;
  };

  const columns: TableColumn[] = [
    { 
      key: 'device_name', 
      title: '设备名称', 
      dataIndex: 'device_name',
      render: (value: string, record: DeviceInstance) => (
        <div className={styles.deviceName}>
          <div className={styles.deviceNameText}>{value || '未命名设备'}</div>
          <div className={styles.deviceType}>{record.device_type || '未知类型'}</div>
        </div>
      )
    },
    { 
      key: 'status', 
      title: '状态', 
      dataIndex: 'status',
      align: 'center',
      render: (value: DeviceInstanceStatus) => getStatusBadge(value)
    },
    { key: 'location', title: '位置', dataIndex: 'location', align: 'center' },
    { key: 'last_seen_at', title: '最后在线', dataIndex: 'last_seen_at', align: 'center' },
    { key: 'ota_status', title: 'OTA状态', dataIndex: 'ota_status', align: 'center' },
    { key: 'created_at', title: '创建时间', dataIndex: 'created_at', align: 'center' }
  ];

  const statusCounts = {
    total: devices.length,
    online: devices.filter(d => d.status === DeviceInstanceStatus.ONLINE).length,
    offline: devices.filter(d => d.status === DeviceInstanceStatus.OFFLINE).length,
    maintenance: devices.filter(d => d.status === DeviceInstanceStatus.MAINTENANCE).length,
    deleted: devices.filter(d => d.status === DeviceInstanceStatus.DELETED).length
  };

  return (
    <div className={styles.container}>
      <div className={styles.header}>
        <div className={styles.headerContent}>
          <h1 className={styles.title}>设备管理</h1>
          <p className={styles.subtitle}>管理和监控您的ESP32设备</p>
        </div>
        
        <div className={styles.stats}>
          <div className={styles.statCard}>
            <div className={styles.statValue}>{statusCounts.total}</div>
            <div className={styles.statLabel}>总设备数</div>
          </div>
          <div className={styles.statCard}>
            <div className={`${styles.statValue} ${styles.statOnline}`}>{statusCounts.online}</div>
            <div className={styles.statLabel}>在线设备</div>
          </div>
          <div className={styles.statCard}>
            <div className={`${styles.statValue} ${styles.statOffline}`}>{statusCounts.offline}</div>
            <div className={styles.statLabel}>离线设备</div>
          </div>
          <div className={styles.statCard}>
            <div className={`${styles.statValue} ${styles.statError}`}>{statusCounts.maintenance}</div>
            <div className={styles.statLabel}>维护中</div>
          </div>
        </div>
      </div>

      <div className={styles.controls}>
        <div className={styles.searchBox}>
          <SearchIcon className={styles.searchIcon} size={20} />
          <input
            type="text"
            placeholder="搜索设备名称、类型或位置..."
            className={styles.searchInput}
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
          />
        </div>
        
        <div className={styles.filterGroup}>
          <label className={styles.filterLabel}>状态筛选:</label>
          <select 
            className={styles.filterSelect}
            value={statusFilter}
            onChange={(e) => setStatusFilter(e.target.value)}
          >
            <option value="all">全部</option>
            <option value={DeviceInstanceStatus.ONLINE}>在线</option>
            <option value={DeviceInstanceStatus.OFFLINE}>离线</option>
            <option value={DeviceInstanceStatus.MAINTENANCE}>维护中</option>
            <option value={DeviceInstanceStatus.DELETED}>已删除</option>
          </select>
        </div>
      </div>

      <div className={styles.tableContainer}>
        <Table
          columns={columns}
          data={filteredDevices}
          loading={loading}
        />
      </div>
    </div>
  );
};

export default DevicePage;
